<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>promise代码的重写(未完成)</title>
</head>

<body>
    <div>
        <span>学习页面</span>
        https://www.bilibili.com/video/BV1Tu411i72B/?spm_id_from=333.337.search-card.all.click&vd_source=e278051a040d115f607ae336fd08bbb6
    </div>
</body>

</html>

<script>
    // promise代码的重写

    class MyPromise {
        constructor(executor) {
            this.state = 'pending'
            this.value = undefined
            this.reason = undefined
            this.onFullFilledCallbacks = []
            this.onRejectedCallbacks = []

            let resolve = (value) => {
                if (this.state !== 'pending') return
                this.state = 'fulfilled'
                this.value = value
                this.onFullFilledCallbacks.forEach(fn => fn())
            }
            let reject = (reason) => {
                if (this.state !== 'pending') return
                this.state = 'rejected'
                this.reason = reason
                this.onRejectedCallbacks.forEach(fn => fn())
            }
            executor(resolve, reject)
        }


        then(onReserved, onRejected) {
            return new MyPromise((resolve, reject) => {
                let x;
                if (this.state === 'fulfilled') {
                    x = onReserved(this.value)
                    resolve(x)
                }
                if (this.state === 'rejected') {
                    x = onRejected(this.reason)
                    // resolve(x)
                }
                if (this.state === 'pending') {
                    this.onFullFilledCallbacks.push(() => {
                        x = onReserved(this.value)
                        // resolve(x)
                    })
                    this.onRejectedCallbacks.push(() => {
                        x = onRejected(this.reason)
                        // resolve(x)
                    })
                }
            })
        }
    }

    // const p1 = new MyPromise((resolve, reject) => {
    //     resolve('结果')
    // }).then(res => {
    //     console.log('这是我的输出值:', res)
    // })

    const p2 = new Promise((resolve, reject) => {
        // resolve('正确')
        reject('错误')
    }).then((res) => {
        return res + 221
    }, (err) => {
        return err + 3
    }).then((res) => {
        console.log('最后在这里输出:', res)
    }, (err) => {
        console.log('输出error结果:', err)
    })

</script>